package com.example.coffeeseller_2.views.customviews;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.beans.Step;
import com.example.coffeeseller_2.utils.JinzhiSwitcher;

import java.util.ArrayList;
import java.util.List;

import cof.ac.inter.CoffMsger;
import cof.ac.inter.ContainerConfig;
import cof.ac.inter.Result;
import cof.ac.inter.StateEnum;

/**
 * Created by Administrator on 2018/6/22.
 */

public class ProductDebugDialog extends Dialog {
    private Context mContext;
    private View view;
    private GridView gridView;
    private TextView tip;

    public ProductDebugDialog(@NonNull Context context) {
        super(context);
        mContext = context;
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = 1500;
        window.setAttributes(params);
    }

    public ProductDebugDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        mContext = context;
    }

    //  UI界面优化
    public void init(List<Coffee> coffees, SendMkCoffeeCommandResult sendMkCoffeeCommandResult) {
        view = LayoutInflater.from(mContext).inflate(R.layout.debug_dialog_product_layout, null, false);
        tip = (TextView) view.findViewById(R.id.tip);
        if (CoffMsger.getInstance().getLastMachineState().getMajorState().getCurStateEnum() != StateEnum.IDLE) {
            if (tip != null) {
                tip.setText("机器出现故障，errorCode= "
                        + JinzhiSwitcher.byte2Hex(CoffMsger.getInstance().getLastMachineState().getMajorState().getHighErr_byte()));
            }
        } else {
            if (tip != null) {
                tip.setText("可制作");
            }
        }
        gridView = (GridView) view.findViewById(R.id.productGrid);
        final Button disBtn = (Button) view.findViewById(R.id.dismiss);
        disBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowing()) {
                    dismiss();
                }
            }
        });
        ProductGridAdapter adapter = new ProductGridAdapter(coffees, mContext, sendMkCoffeeCommandResult);
        gridView.setAdapter(adapter);
        setContentView(view);
        setTitle("咖啡制作测试");
        initListener();
        if (!isShowing()) {
            show();
        }
    }


    private void initListener() {
        setCanceledOnTouchOutside(false);
    }

    class ProductGridAdapter extends BaseAdapter {
        List<Coffee> coffees;
        Context context;
        CoffMsger coffMsger;
        SendMkCoffeeCommandResult sendMkCoffeeCommandResult;

        public ProductGridAdapter(List<Coffee> coffees, Context context, SendMkCoffeeCommandResult sendMkCoffeeCommandResult) {
            this.coffees = coffees;
            this.context = context;
            this.coffMsger = CoffMsger.getInstance();
            this.sendMkCoffeeCommandResult = sendMkCoffeeCommandResult;
        }

        @Override
        public int getCount() {
            return coffees.size();
        }

        @Override
        public Object getItem(int position) {
            return coffees.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ProductGridAdapter.ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.debug_grid_button, null);
                viewHolder = new ProductGridAdapter.ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ProductGridAdapter.ViewHolder) convertView.getTag();
            }
            viewHolder.button.setText(coffees.get(position).name);
            viewHolder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (coffMsger.getLastMachineState().getMajorState().getCurStateEnum() != StateEnum.IDLE) {
                        if (tip != null) {
                            tip.setText("机器出现故障，errorCode= "
                                    + JinzhiSwitcher.byte2Hex(coffMsger.getLastMachineState().getMajorState().getHighErr_byte()));

                            new AlertDialog.Builder(context).setMessage("机器有故障，继续制作？")
                                    .setNegativeButton("取消", new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).setPositiveButton("继续", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mkCoffee(position);
                                }
                            }).create().show();
                        }
                    }else{
                        mkCoffee(position);
                    }



                }
            });
            return convertView;
        }

        private void mkCoffee(int position) {
            List<ContainerConfig> containerConfigs = new ArrayList<ContainerConfig>();
            for (Step step : coffees.get(position).getStepList()) {
                ContainerConfig containerConfig = new ContainerConfig();
                containerConfig.setStir_speed(step.getContainerConfig().getStir_speed());
                containerConfig.setWater_capacity(step.getContainerConfig().getWater_capacity());
                containerConfig.setContainer(step.getContainerConfig().getContainer());
                containerConfig.setRotate_speed(step.getContainerConfig().getRotate_speed());
                containerConfig.setMaterial_time(step.getContainerConfig().getMaterial_time());
                containerConfig.setWater_interval(step.getContainerConfig().getWater_interval());
                containerConfig.setWater_type(step.getContainerConfig().getWater_type());
                containerConfigs.add(containerConfig);
            }

            Result result = coffMsger.mkCoffee(containerConfigs);

            if (result.getCode() == Result.SUCCESS) {
                if (tip != null) {
                    tip.setText("send mkCoffee comd success !");
                }
            } else {
                if (tip != null) {
                    tip.setText("send mkCoffee comd failed !");
                }
            }

            DealRecorder dealRecorder = new DealRecorder();
            dealRecorder.setCoffee(coffees.get(position));
            dealRecorder.setContainerConfigs(containerConfigs);
            if (sendMkCoffeeCommandResult != null) {
                sendMkCoffeeCommandResult.getResult(dealRecorder, result);
            }
        }

        class ViewHolder {
            public Button button;

            public ViewHolder(View view) {
                button = (Button) view.findViewById(R.id.product);
            }
        }
    }

    public interface SendMkCoffeeCommandResult {
        void getResult(DealRecorder dealRecorder, Result result);
    }
}
